<!DOCTYPE html>
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" type="text/css" href="resources/tablet.css">
<link rel="stylesheet" type="text/css" href="resources/transition.css">
<script src="resources/perf_test_helper.js"></script>
<style>
show + target {
  opacity: 1;
}
hide + target {
  opacity: 0;
}
show, hide {
  display: none;
}
</style>

<container id="container"></container>

<script>
var N = PerfTestHelper.getN(1000);
var duration = 1000;
var stash = {SHOW: [], HIDE: []};
var targets = [];

for (var i = 0; i < N; i++) {
  stash.HIDE.push(document.createElement('hide'));
  var show = document.createElement('show');
  container.appendChild(show);
  var target = document.createElement('target');
  container.appendChild(target);
  targets.push(target);
}

function startTransition(target, fastForward) {
  var state = target.previousSibling;
  stash[state.tagName].push(state);
  state.remove();
  var newState = state.tagName == 'SHOW' ? stash.HIDE.pop() : stash.SHOW.pop();
  container.insertBefore(newState, target);
  target.style.transitionDelay = -fastForward + 'ms';
}

requestAnimationFrame(function(time) {
  var startTime = time - duration;
  var step = 0;

  function staggeredStart(time) {
    var elapsed = time - startTime;
    var targetStep = Math.floor(N * elapsed / duration);
    step = Math.max(targetStep - N, step);
    for (; step < targetStep; step++) {
      startTransition(targets[step % N], elapsed - (step / N * duration));
    }
    requestAnimationFrame(staggeredStart);
  }
  staggeredStart(time);
});

PerfTestHelper.signalReady();
</script>
